const routes = [
  {
    name: 'index',
    label: 'AceClub',
    path: '/',
    exact: true,
    component: () => import('../routes/IndexPage'),
  },
  {
    name: 'activity',
    label: '活动列表',
    path: '/activity',
    exact: true,
    models: ['activity'],
    component: () => import('../routes/Activity/List'),
    routes: [
      {
        name: 'activity.detail',
        label: '活动详情',
        path: '/activity/:id',
        exact: true,
        component: () => import('../routes/Activity/Detail'),
      },
      {
        name: 'activity.result',
        path: '/activity/apply/result',
        exact: true,
        component: () => import('../routes/Activity/Result'),
      },
    ],
  },
  {
    name: 'member',
    label: '成为会员',
    path: '/member',
    models: ['member'],
    routes: [
      {
        name: 'member.join',
        label: '成为会员',
        path: '/member/joinus',
        exact: true,
        component: () => import('../routes/Member/JoinUs'),
      },
      {
        name: 'member.result',
        label: '申请结果',
        path: '/member/result',
        exact: true,
        component: () => import('../routes/Member/Result'),
      },
    ],
  },
  {
    name: 'mine',
    label: '我的',
    path: '/mine',
    exact: true,
    models: ['member'],
    component: () => import('../routes/Mine'),
    routes: [
      {
        name: 'mine.detail',
        label: '我的详细信息',
        path: '/mine/detail',
        exact: true,
        component: () => import('../routes/Mine/Detail'),
      },
    ],
  },
];

// 递归查询 name 相同的 route
const routeRecursive = (route, name) => {
  if (!route || !name) return undefined;

  if (route.name === name) return route;

  if (!route.routes || !route.routes.length) return undefined;

  return route.routes.map(x => routeRecursive(x, name)).filter(x => x)[0];
};

export function getRoute(r) {
  let name = '';
  let params = '';
  let query = '';
  if (typeof r === 'string') {
    name = r;
  } else {
    name = r.name;
    params = r.params;
    query = r.query;
  }

  let { path = '' } = routes.map(x => routeRecursive(x, name)).filter(x => x)[0] || {};
  if (path.indexOf(':')) {
    path = Object.keys(params).reduce((p, k) => {
      return p.replace(`:${k}`, params[k]);
    }, path);
  }

  if (query) {
    const searchStr = Object.keys(query).reduce((s, k) => {
      const val = query[k];
      if (Array.isArray(val)) {
        return [...s, ...val.map(v => `${k}=${v}`)];
      }

      return [...s, `${k}=${val}`];
    }, []).join('&');

    const joinSign = path.indexOf('?') > -1 ? '&' : '?';
    path = path + joinSign + searchStr;
  }

  return path;
}

export default routes;
